package com.chenpp.redis.lru;

/**
 * @Description
 * @Author chenpp
 * @Date 2019/10/21 17:56
 * 定义一个双向链表
 */
public class DoubleLinkedList<K,V> {

    transient Node<K,V> first;
    transient Node<K,V> last;
    transient int size;

    public void addFirst(Node node) {
        if (first == null) {
            first = node;
            last = node;
        } else {
            Node oldFirst = first;
            oldFirst.setPre(node);
            node.setNext(oldFirst);
            first = node;
        }
        size++;
    }


    public Node remove(Node node){
        if(first == null || node == null){
            return null;
        }
        Node n = first;
        while(n != null){
            if(n.getValue().equals(node.getValue()) && n.getKey().equals(node.getKey())){
                if(n.getPre() != null)
                   n.getPre().setNext(n.getNext());
                if(n.getNext() != null)
                    n.getNext().setPre(n.getPre());
                size--;
                return n;
            }
            n = n.getNext();
        }
        return null;
    }

    public Node moveToHead(Node node){
        if(node == first){
            return node;
        }
        if( node == last){
            last = node.getPre();
        }else{
            node.getNext().setPre(node.getPre());
        }
        node.getPre().setNext(node.getNext());
        node.setPre(null);
        node.setNext(first);
        first = node;
        return node;
    }

    public Node removeLast(){
        if(last == null){
            return null;
        }
        Node newLast = last.getPre();
        Node lastNode = last;
        lastNode.setPre(null);
        newLast.setNext(null);
        last = newLast;
        size--;
        return lastNode;
    }

    public int size(){
        return size;
    }
}
